package com.eonmind.user.utils;

import com.eonmind.common.provider.entity.user.UserLoginRecord;
import jakarta.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class FetchUserLoginRecordUtil {
    public static UserLoginRecord getUserLoginRecord(HttpServletRequest request) {

        UserLoginRecord userLoginRecord = new UserLoginRecord();
        //获取登录IP
        String ipAddress = getClientIpAddress(request);
        String[] ips = ipAddress.split(",");
        ipAddress = ips[0];
        //获取登录设备信息
        UserLoginRecord.DeviceInfo device = getDeviceInfo(request);
        //获取登陆位置
        String location = getLocationInfo(ipAddress);

        userLoginRecord.setLoginIp(ipAddress);
        userLoginRecord.setLoginDevice(device);
        userLoginRecord.setLoginLocation(location);

        return userLoginRecord;
    }

    /**
     * 获取客户端IP地址
     *
     * @param request HttpServletRequest
     * @return 客户端IP地址
     */
    private static String getClientIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }


    /**
     * 获取登录地点
     *
     * @param ipAddress 客户端IP地址
     * @return 登录地点信息
     */
    private static String getLocationInfo(String ipAddress) {
        try {
            URL url = new URL("http://ip-api.com/json/" + ipAddress + "?lang=zh-CN");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            connection.disconnect();
            return parseLocationInfo(content.toString());
        } catch (Exception e) {
            return "未知";
        }
    }

    /**
     * 解析登录地点信息
     *
     * @param json JSON字符串
     * @return 登录地点信息
     */
    private static String parseLocationInfo(String json) {
        try {
            // 简单的JSON解析
            String country = getValueFromJson(json, "country");
            String regionName = getValueFromJson(json, "regionName");
            String city = getValueFromJson(json, "city");

            return country + " " + regionName + " " + city;
        } catch (Exception e) {
            return "未知";
        }
    }


    /**
     * 从JSON字符串中提取值
     *
     * @param json JSON字符串
     * @param key  键
     * @return 值
     */
    private static String getValueFromJson(String json, String key) {
        String patternString = "\"" + key + "\":\"([^\"]*)\"";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(json);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "未知";
    }

    /**
     * 获取设备信息
     *
     * @param request HttpServletRequest
     * @return DeviceInfo对象
     */
    public static UserLoginRecord.DeviceInfo getDeviceInfo(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        UserLoginRecord.DeviceInfo deviceInfo = new UserLoginRecord.DeviceInfo();

        if (userAgent == null || userAgent.isEmpty()) {
            deviceInfo.setOperatingSystem("Unknown");
            deviceInfo.setBrowser("Unknown");
            return deviceInfo;
        }
        // 规范化用户代理字符串
        userAgent = userAgent.toLowerCase();

        // 解析操作系统信息
        parseOperatingSystem(userAgent, deviceInfo);

        // 解析浏览器信息
        parseBrowser(userAgent, deviceInfo);

        // 解析设备类型
        parseDeviceType(userAgent, deviceInfo);

        return deviceInfo;
    }

    /**
     * 解析操作系统信息
     */
    private static void parseOperatingSystem(String userAgent, UserLoginRecord.DeviceInfo deviceInfo) {
        // Windows
        if (userAgent.contains("windows")) {
            deviceInfo.setOperatingSystem("Windows");
            if (userAgent.contains("windows nt 10.0")) {
                deviceInfo.setOsVersion("10");
            } else if (userAgent.contains("windows nt 6.3")) {
                deviceInfo.setOsVersion("8.1");
            } else if (userAgent.contains("windows nt 6.2")) {
                deviceInfo.setOsVersion("8");
            } else if (userAgent.contains("windows nt 6.1")) {
                deviceInfo.setOsVersion("7");
            } else {
                deviceInfo.setOsVersion("Unknown");
            }
        }
        // Mac OS
        else if (userAgent.contains("mac os x")) {
            deviceInfo.setOperatingSystem("Mac OS");
            Matcher matcher = Pattern.compile("mac os x (\\d+[._]\\d+[._]\\d+)").matcher(userAgent);
            if (matcher.find()) {
                deviceInfo.setOsVersion(matcher.group(1).replace("_", "."));
            } else {
                deviceInfo.setOsVersion("Unknown");
            }
        }
        // iOS
        else if (userAgent.contains("iphone") || userAgent.contains("ipad")) {
            deviceInfo.setOperatingSystem("iOS");
            Matcher matcher = Pattern.compile("os (\\d+[._]\\d+[._]\\d+)").matcher(userAgent);
            if (matcher.find()) {
                deviceInfo.setOsVersion(matcher.group(1).replace("_", "."));
            }
        }
        // Android
        else if (userAgent.contains("android")) {
            deviceInfo.setOperatingSystem("Android");
            Matcher matcher = Pattern.compile("android (\\d+[.]\\d+)").matcher(userAgent);
            if (matcher.find()) {
                deviceInfo.setOsVersion(matcher.group(1));
            }
        }
        // Linux
        else if (userAgent.contains("linux")) {
            deviceInfo.setOperatingSystem("Linux");
            deviceInfo.setOsVersion("Unknown");
        }
        // 其他
        else {
            deviceInfo.setOperatingSystem("Unknown");
            deviceInfo.setOsVersion("Unknown");
        }
    }

    /**
     * 解析浏览器信息
     */
    private static void parseBrowser(String userAgent, UserLoginRecord.DeviceInfo deviceInfo) {
        // Chrome
        if (userAgent.contains("chrome") && !userAgent.contains("edge") && !userAgent.contains("opr")) {
            deviceInfo.setBrowser("Chrome");
            Matcher matcher = Pattern.compile("chrome/(\\d+[.]\\d+)").matcher(userAgent);
            if (matcher.find()) {
                deviceInfo.setBrowserVersion(matcher.group(1));
            }
        }
        // Firefox
        else if (userAgent.contains("firefox")) {
            deviceInfo.setBrowser("Firefox");
            Matcher matcher = Pattern.compile("firefox/(\\d+[.]\\d+)").matcher(userAgent);
            if (matcher.find()) {
                deviceInfo.setBrowserVersion(matcher.group(1));
            }
        }
        // Safari
        else if (userAgent.contains("safari") && !userAgent.contains("chrome")) {
            deviceInfo.setBrowser("Safari");
            Matcher matcher = Pattern.compile("version/(\\d+[.]\\d+)").matcher(userAgent);
            if (matcher.find()) {
                deviceInfo.setBrowserVersion(matcher.group(1));
            }
        }
        // Edge
        else if (userAgent.contains("edge")) {
            deviceInfo.setBrowser("Edge");
            Matcher matcher = Pattern.compile("edge/(\\d+[.]\\d+)").matcher(userAgent);
            if (matcher.find()) {
                deviceInfo.setBrowserVersion(matcher.group(1));
            }
        }
        // Opera
        else if (userAgent.contains("opr") || userAgent.contains("opera")) {
            deviceInfo.setBrowser("Opera");
            Matcher matcher = Pattern.compile("(?:opr|opera)/(\\d+[.]\\d+)").matcher(userAgent);
            if (matcher.find()) {
                deviceInfo.setBrowserVersion(matcher.group(1));
            }
        }
        // 其他
        else {
            deviceInfo.setBrowser("Unknown");
            deviceInfo.setBrowserVersion("Unknown");
        }
    }

    /**
     * 解析设备类型
     */
    private static void parseDeviceType(String userAgent, UserLoginRecord.DeviceInfo deviceInfo) {
        if (userAgent.contains("mobile")) {
            deviceInfo.setDeviceType("Mobile");
        } else if (userAgent.contains("tablet")) {
            deviceInfo.setDeviceType("Tablet");
        } else {
            deviceInfo.setDeviceType("Desktop");
        }
    }
}
